package com.niit.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.util.Base64;

import static com.niit.utils.FileHashCal.NormalConfig.avatarDir;

public class FileHashCal {
	public static String calculateFileHash(File file, String algorithm) throws Exception {
		MessageDigest digest = MessageDigest.getInstance(algorithm);
		try (FileInputStream fis = new FileInputStream(file)) {
			byte[] buffer = new byte[8192];
			int bytesRead;
			while ((bytesRead = fis.read(buffer)) != -1) {
				digest.update(buffer, 0, bytesRead); // 分块更新哈希
			}
		}
		byte[] hashBytes = digest.digest();
		return new BigInteger(1, hashBytes).toString(16); // 转为16进制字符串
	}

	public static String getHashAndSave(MultipartFile file, String cacheDir) {
		try {
			if(file != null){
				File dir = new File(NormalConfig.resumeDir);
				if (!dir.exists()) dir.mkdirs();

				String originalFilename = file.getOriginalFilename();
				if (originalFilename == null || originalFilename.isEmpty()) return null;
				String savedFilename = System.currentTimeMillis() + "_" + originalFilename; // 组合新名称
				File targetFile = new File(cacheDir + File.separator + savedFilename);

				file.transferTo(targetFile.getAbsoluteFile());
				File hashFile = null;

				String fileHash = calculateFileHash(targetFile,"SHA-256");
				hashFile = new File(cacheDir + File.separator + fileHash + originalFilename.substring(originalFilename.lastIndexOf(".")));
				boolean b = targetFile.renameTo(hashFile);
				if(!b) targetFile.delete();
				return hashFile.getName();
			}
		}catch (Exception ignored){}
		return null;
	}

	public static String turnToBase64(String avatarHash) {
		try {
			byte[] bytes = Files.readAllBytes(Paths.get(avatarDir + File.separator + avatarHash));
			Base64.Encoder encoder = Base64.getEncoder();
			return encoder.encodeToString(bytes);
		}catch (Exception ignored){}
		return null;
	}

	public static class NormalConfig {
		public static final String avatarDir = "./cache/avatar";
		public static final String resumeDir = "./cache/resume";
	}
}
